package com.sushi.bigblog.filedb;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * User: bianpeng
 * Date: 11-12-6
 */
public class Db {
    private static final int ENTRY_SIZE = 24;
    public static final int FLAG_GZIPPED = 0x00000001;
    public static final int FLAG_DELETED = 0x00000010;
    private int version = 0x000001;
    private static final int SEP = '\n';

    private RandomAccessFile entryFile;
    private RandomAccessFile contentFile;
    // 索引文件
    private LazyDbEntry lazyDbEntry;

    public Db(File entry, File content) throws IOException {
        entryFile = new RandomAccessFile(entry, "rwd");
        if (entryFile.length() == 0) {
            entryFile.writeInt(version);
        } else {
            int entry_version = entryFile.readInt();
            assert entry_version == version;
        }
        lazyDbEntry = new LazyDbEntry(entryFile);

        contentFile = new RandomAccessFile(content, "rwd");
        if (content.length() == 0) {
            contentFile.writeInt(version);
        } else {
            int content_version = contentFile.readInt();
            assert content_version == version;
        }
    }

    public byte[] loadContent(DbEntry entry) throws IOException {
        contentFile.seek(entry.getOffset());
        byte[] data = new byte[entry.getSize()];
        contentFile.read(data);
        return data;
    }

    public DbEntry appendContent(byte[] data, int owner, int flag) throws IOException {
        long offset = contentFile.length();
        if (offset == 0) {
            entryFile.writeInt(version);
            offset += 4;
        }
        contentFile.seek(offset);
        contentFile.write(data);
        contentFile.writeByte(SEP); // end with '\0'
        DbEntry entry = new DbEntry(owner, offset, data.length, System.currentTimeMillis(), flag);
        lazyDbEntry.addEntry(entry);
        return entry;
    }

    public void close() throws IOException {
        entryFile.close();
        contentFile.close();
    }

    public DbEntry findBlog(long offset) throws IOException {
        return lazyDbEntry.findEntry(offset);
    }

    public List<DbEntry> getEntryList(int offset, int limit) throws IOException {
        return lazyDbEntry.getEntryList(offset, limit);
    }
}
